/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package digitaldreamers.libraries.games.servers.networkmanagement.packets.receiving;

import digitaldreamers.libraries.games.servers.networkmanagement.abstracts.IConnectionHandler;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

/**
 * Abstract class for all receivable packet classes.
 *
 * @author DaoLe
 */
public abstract class AbReceivablePacket {
    // Packet ID.
    protected int mPacketId;
    protected IConnectionHandler mConnectionHandler;

    /**
     * Create a new instance.
     *
     * @param pConnectionHandler The ConnecionHandler object that received this
     * packet.
     */
    public AbReceivablePacket(IConnectionHandler pConnectionHandler) {
        mConnectionHandler = pConnectionHandler;
    }

    /**
     * Read packet data.
     *
     * @param pData The data sent from client.
     * @throws IOException Error that occurred while trying to parse data sent
     * from client.
     */
    public void fromByteArray(byte[] pData) throws IOException {
        ByteArrayInputStream BAIS = new ByteArrayInputStream(pData);
        DataInputStream DIS = new DataInputStream(BAIS);
        try {
            readData(DIS);
        } catch (IOException ex) {
            throw ex;
        } finally {
            DIS.close();
        }
    }

    /**
     * Execute the logic. Should implement this method.
     * @throws Exception Error that occurred while executing the logic.
     */
    public abstract void execute() throws Exception;
    
    /**
     * Read packet data.
     * @param pDIS Input stream.
     * @throws IOException Error that occurred while reading data sent
     */
    protected abstract void readData(DataInputStream pDIS) throws IOException;
}